package com.ldy.util;

import java.lang.reflect.Field;
import java.util.ArrayList;

import android.text.TextUtils;

import com.ldy.annotation.Table;
import com.ldy.test.Model;

public final class AnnotationUtil {

	/**
	 * 获取表名
	 * 
	 * @param clz
	 * @return
	 */
	public static String getTableName(Class clz) {
		Table table = (Table) clz.getAnnotation(Table.class);
		return table.tableName();
	}

	/**
	 * 获取全部注解的字段
	 * 
	 * @param clz
	 * @return
	 */
	public static ArrayList<String> getFields(Class clz) {
		ArrayList<String> list = new ArrayList<String>();
		Field[] fs = clz.getDeclaredFields();

		for (Field field : fs) {
			com.ldy.annotation.Field f = field.getAnnotation(com.ldy.annotation.Field.class);
			if (f != null) {
				list.add(f.columnName().equals("") ? field.getName() : f.columnName());
			}
		}

		return list;
	}

	public static String getFieldName(Field field) {
		com.ldy.annotation.Field f = field.getAnnotation(com.ldy.annotation.Field.class);
		if (f == null)
			return null;
		if (TextUtils.isEmpty(f.columnName())) {
			return field.getName();
		} else {
			return f.columnName();
		}
	}

	/**
	 * 字段模型的描述
	 * 
	 * @param field
	 * @return
	 */
	public static com.ldy.db.model.Model getModel(Field field) {

		com.ldy.annotation.Field f = field.getAnnotation(com.ldy.annotation.Field.class);
		if (f == null)
			return null;

		com.ldy.db.model.Model model = new com.ldy.db.model.Model();
		model.setColumnName(f.columnName().equals("") ? field.getName() : f.columnName());
		model.setFieldName(field.getName().toString());
		model.setGeneratedId(f.generatedId());
		model.setId(f.id());
		model.setWidth(f.width());
		return model;

	} 

	/**
	 * 字段模型的描述
	 * 
	 * @param field
	 * @return
	 */
	public static ArrayList<com.ldy.db.model.Model> getModel(Class clz) {
		ArrayList<com.ldy.db.model.Model> list = new ArrayList<com.ldy.db.model.Model>();
		Field[] fs = clz.getDeclaredFields();
		for (Field field : fs) {
			com.ldy.annotation.Field f = field.getAnnotation(com.ldy.annotation.Field.class);
			if (f != null) {
				com.ldy.db.model.Model model = new com.ldy.db.model.Model();
				model.setColumnName(f.columnName().equals("") ? field.getName() : f.columnName());
				model.setFieldName(field.getName().toString());
				model.setGeneratedId(f.generatedId());
				model.setId(f.id());
				model.setWidth(f.width());
				list.add(model);
			}
		}
		return list;
	}
}
